import { useEffect, useState } from 'react';
import MLog from 'renderer/util/main-log';
import { FileType } from '../../main/const';

export function useChooseDir(initDirPath: string): [string, () => void] {
  const [dirPath, setDirPath] = useState('');
  useEffect(() => {
    setDirPath(initDirPath);
  }, [initDirPath]);
  const startChoose = () => {
    window.electronAPI.ipcRenderer
      .chooseDir()
      .then((res) => {
        setDirPath(res);
      })
      .catch((err) => {
        MLog.e(err);
      });
  };
  return [dirPath, startChoose];
}

export function useChooseSingleFile(
  initFilePath: string,
  fileType: FileType
): [string, () => Promise<string>] {
  const [filePath, setFilePath] = useState('');
  useEffect(() => {
    setFilePath(initFilePath);
  }, [initFilePath]);
  const startChoose = () => {
    return new Promise<string>((resolve, reject) => {
      window.electronAPI.ipcRenderer
        .chooseSingleFile(fileType)
        .then((res) => {
          setFilePath(res);
          resolve(res);
        })
        .catch((err) => {
          MLog.e(err);
          reject(err);
        });
    });
  };
  return [filePath, startChoose];
}
